package com.ruoyi.part.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.AutofillUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.snowFlake.SnowFlakeUtil;
import com.ruoyi.fund.domain.DmsFund;
import com.ruoyi.fund.domain.DmsFundRecord;
import com.ruoyi.fund.service.IDmsFundRecordService;
import com.ruoyi.fund.service.IDmsFundService;
import com.ruoyi.part.domain.DmsPartStorageInfo;
import com.ruoyi.part.domain.DmsPartsPurchaseOrder;
import com.ruoyi.part.domain.DmsPartsPurchaseOrderDetail;
import com.ruoyi.part.mapper.DmsPartsPurchaseOrderMapper;
import com.ruoyi.part.service.IDmsPartStorageInfoService;
import com.ruoyi.part.service.IDmsPartsPurchaseOrderDetailService;
import com.ruoyi.part.service.IDmsPartsPurchaseOrderService;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 零件采购Service业务层处理
 * 
 * @author liuchuanfa
 * @date 2024-03-17
 */
@Service
public class DmsPartsPurchaseOrderServiceImpl extends ServiceImpl<DmsPartsPurchaseOrderMapper,DmsPartsPurchaseOrder> implements IDmsPartsPurchaseOrderService
{
    @Autowired
    private DmsPartsPurchaseOrderMapper dmsPartsPurchaseOrderMapper;
    @Autowired
    private AutofillUtil autofillUtil;
    @Autowired
    private IDmsPartsPurchaseOrderDetailService iDmsPartsPurchaseOrderDetailService;
    @Autowired
    private IDmsPartStorageInfoService iDmsPartStorageInfoService;
    @Autowired
    private IDmsFundRecordService iDmsFundRecordService;
    @Autowired
    private IDmsFundService iDmsFundService;
    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 查询零件采购
     * 
     * @param id 零件采购主键
     * @return 零件采购
     */
    @Override
    public DmsPartsPurchaseOrder selectDmsPartsPurchaseOrderById(Long id)
    {
        //查询采购订单信息
        return dmsPartsPurchaseOrderMapper.selectDmsPartsPurchaseOrderById(id);
    }

    /**
     * 根据id查询零件信息
     *
     * @param orderDetailpartNos
     * @return {@link List }<{@link DmsPartStorageInfo }>
     * @author liuchuanfa
     * @since 2024/03/19
     */
    @Override
    public List<DmsPartStorageInfo> getPartsInfoByIds(String[] orderDetailpartNos) {
        //查询采购订单详细信息
        List<DmsPartStorageInfo> list = iDmsPartStorageInfoService.lambdaQuery().in(DmsPartStorageInfo::getPartNo, orderDetailpartNos).orderByDesc(DmsPartStorageInfo::getCreateTime).list();
        return list;
    }

    /**
     * 查询零件采购列表
     * 
     * @param dmsPartsPurchaseOrder 零件采购
     * @return 零件采购
     */
    @Override
    public List<DmsPartsPurchaseOrder> selectDmsPartsPurchaseOrderList(DmsPartsPurchaseOrder dmsPartsPurchaseOrder)
    {
        return dmsPartsPurchaseOrderMapper.selectDmsPartsPurchaseOrderList(dmsPartsPurchaseOrder);
    }

    /**
     * 新增零件采购
     * 
     * @param dmsPartsPurchaseOrder 零件采购
     * @return 结果
     */
    @Transactional
    @Override
    public boolean insertDmsPartsPurchaseOrder(DmsPartsPurchaseOrder dmsPartsPurchaseOrder)
    {
        if (dmsPartsPurchaseOrder.getDmsPartsPurchaseOrderDetailList().size()<=0){
            throw new ServiceException("新建采购订单至少需要一个零件！");
        }

        //判断采购新建状态是否为待审核，不是就报错 “新建时状态只能时待审核”
        if (!dmsPartsPurchaseOrder.getPurchaseStatus().equals(0)){
            throw new ServiceException("新建采购订单的状态只可以是待审核！");
        }
        //新增自动填充
        autofillUtil.autoFillCreate(dmsPartsPurchaseOrder);
        //添加厂/店端信息（厂端信息，从零件的所属方来得到）
        List<DmsPartsPurchaseOrderDetail> purchaseOrderDetailList = dmsPartsPurchaseOrder.getDmsPartsPurchaseOrderDetailList();
        List<String> partNos = purchaseOrderDetailList.stream().map(i -> i.getPartNo()).collect(Collectors.toList());
        List<DmsPartStorageInfo> partStorageInfoList = iDmsPartStorageInfoService.lambdaQuery().in(DmsPartStorageInfo::getPartNo, partNos).list();
        Long factoryId = partStorageInfoList.get(0).getFactoryId();
        dmsPartsPurchaseOrder.setFactoryId(factoryId);
        dmsPartsPurchaseOrder.setDealerId(SecurityUtils.getLoginUser().getUser().getDept().getParentId());
        dmsPartsPurchaseOrder.setDealerName(iSysDeptService.selectDeptById(SecurityUtils.getLoginUser().getUser().getDept().getParentId()).getDeptName());
        int rows = dmsPartsPurchaseOrderMapper.insertDmsPartsPurchaseOrder(dmsPartsPurchaseOrder);
        insertDmsPartsPurchaseOrderDetail(dmsPartsPurchaseOrder); //保存采购订单详情

        return true;
    }

    /**
     * 修改零件采购
     * 
     * @param dmsPartsPurchaseOrder 零件采购
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateDmsPartsPurchaseOrder(DmsPartsPurchaseOrder dmsPartsPurchaseOrder)
    {
        //根据采购订单id查询数据，比较状态是否逐层递进（不可跨状态,也不可逆
        DmsPartsPurchaseOrder dealerWholePurchaseDB = selectDmsPartsPurchaseOrderById(dmsPartsPurchaseOrder.getId());
        Integer StatusDB = dealerWholePurchaseDB.getPurchaseStatus();
        if (StatusDB>=dmsPartsPurchaseOrder.getPurchaseStatus()) throw new ServiceException("采购订单不可逆");
        if ((StatusDB+1)!=dmsPartsPurchaseOrder.getPurchaseStatus()) throw new ServiceException("采购订单不可跨状态修改");

        //查询零件单价
        double sum = dmsPartsPurchaseOrder.getDmsPartsPurchaseOrderDetailList().stream().mapToDouble(i -> {
            //根据vin，查询价格，并返回
            DmsPartStorageInfo partStorageInfo = iDmsPartStorageInfoService.lambdaQuery().eq(DmsPartStorageInfo::getPartNo, i.getPartNo()).one();
            if (partStorageInfo == null) {
                throw new ServiceException("库存中查询不到该零件！" + i.getPartNo());
            }
            if (partStorageInfo.getOutletPrice() == null) {
                throw new ServiceException("库存中查询不到该零件的价格！" + i.getPartNo());
            }
            return partStorageInfo.getOutletPrice();
        }).sum();

        //为采购表计算 采购零件的数量、采购总价
        dmsPartsPurchaseOrder.setWholePurchaseNumber(dmsPartsPurchaseOrder.getDmsPartsPurchaseOrderDetailList().size());
        dmsPartsPurchaseOrder.setPurchasePrice(sum * dmsPartsPurchaseOrder.getDmsPartsPurchaseOrderDetailList().size());

        //采购订单详细删除，并添加新的
        dmsPartsPurchaseOrderMapper.deleteDmsPartsPurchaseOrderDetailByPurchaseId(dmsPartsPurchaseOrder.getId());
        insertDmsPartsPurchaseOrderDetail(dmsPartsPurchaseOrder);
        //添加审核人id、审核人名、审核时间
        dmsPartsPurchaseOrder.setAuditorId(SecurityUtils.getLoginUser().getUser().getUserId());
        dmsPartsPurchaseOrder.setAuditorName(SecurityUtils.getLoginUser().getUser().getUserName());
        dmsPartsPurchaseOrder.setAuditorTime(new Date());
        //更新采购订单
        autofillUtil.autoFillUpdate(dmsPartsPurchaseOrder);
        dmsPartsPurchaseOrderMapper.updateDmsPartsPurchaseOrder(dmsPartsPurchaseOrder);

        //修改零件的状态
        List<DmsPartsPurchaseOrderDetail> partsPurchaseOrderDetailList = iDmsPartsPurchaseOrderDetailService.lambdaQuery().in(DmsPartsPurchaseOrderDetail::getPartNo,dmsPartsPurchaseOrder.getId()).list();
        List<String> partNos = partsPurchaseOrderDetailList.stream().map(i -> i.getPartNo()).collect(Collectors.toList());
        //①采购订单已发货就把零件状态改为经销商在途
        if (dmsPartsPurchaseOrder.getPurchaseStatus().equals(6)){
            iDmsPartStorageInfoService.lambdaUpdate().set(DmsPartStorageInfo::getPartStatus,1).in(DmsPartStorageInfo::getPartNo,partNos).update();
        }
        //②采购订单已签收，就改零件状态为经销商在库
        if (dmsPartsPurchaseOrder.getPurchaseStatus().equals(7)){
            iDmsPartStorageInfoService.lambdaUpdate()
                    .set(DmsPartStorageInfo::getPartStatus,2)
                    .set(DmsPartStorageInfo::getInventoryType,"店端")
                    .in(DmsPartStorageInfo::getPartNo,partNos)
                    .update();
        }

        return true;
    }

    /**
     * 批量删除零件采购
     * 
     * @param ids 需要删除的零件采购主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDmsPartsPurchaseOrderByIds(Long[] ids)
    {
        dmsPartsPurchaseOrderMapper.deleteDmsPartsPurchaseOrderDetailByPurchaseIds(ids);
        return dmsPartsPurchaseOrderMapper.deleteDmsPartsPurchaseOrderByIds(ids);
    }

    /**
     * 删除零件采购信息
     * 
     * @param id 零件采购主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDmsPartsPurchaseOrderById(Long id)
    {
        dmsPartsPurchaseOrderMapper.deleteDmsPartsPurchaseOrderDetailByPurchaseId(id);
        return dmsPartsPurchaseOrderMapper.deleteDmsPartsPurchaseOrderById(id);
    }

    /**
     * 新增零件采购详细信息
     * 
     * @param dmsPartsPurchaseOrder 零件采购对象
     */
    public void insertDmsPartsPurchaseOrderDetail(DmsPartsPurchaseOrder dmsPartsPurchaseOrder)
    {
        List<DmsPartsPurchaseOrderDetail> dmsPartsPurchaseOrderDetailList = dmsPartsPurchaseOrder.getDmsPartsPurchaseOrderDetailList();
        Long id = dmsPartsPurchaseOrder.getId();
        if (StringUtils.isNotNull(dmsPartsPurchaseOrderDetailList))
        {
            List<DmsPartsPurchaseOrderDetail> list = new ArrayList<DmsPartsPurchaseOrderDetail>();
            Long detailId = SnowFlakeUtil.getDefaultSnowFlakeId();
            for (DmsPartsPurchaseOrderDetail dmsPartsPurchaseOrderDetail : dmsPartsPurchaseOrderDetailList)
            {
//                //新增自动填充
                autofillUtil.autoFillCreate(dmsPartsPurchaseOrderDetail);
                //由于时间太短，产生了重复的雪花id，所以这里自动填充填充雪花算法+1
                dmsPartsPurchaseOrderDetail.setId(detailId++);
                dmsPartsPurchaseOrderDetail.setPurchaseId(id);
                list.add(dmsPartsPurchaseOrderDetail);
            }
            if (list.size() > 0)
            {
                dmsPartsPurchaseOrderMapper.batchDmsPartsPurchaseOrderDetail(list);
            }
        }
    }

    /**
     *
     * 订单配件/订单扣款
     * @param id
     * @return {@link Boolean }
     * @author liuchuanfa
     * @since 2024/03/19
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean purchaseVehicleById(Long id) {
        //根据订单id查询订单，再修改订单状态
        DmsPartsPurchaseOrder dmsPartsPurchaseOrder = selectDmsPartsPurchaseOrderById(id);
        int purchaseStatus = dmsPartsPurchaseOrder.getPurchaseStatus();
        DmsPartsPurchaseOrder dmsPartsPurchaseOrderNew = new DmsPartsPurchaseOrder();
        BeanUtil.copyProperties(dmsPartsPurchaseOrder,dmsPartsPurchaseOrderNew);
        dmsPartsPurchaseOrderNew.setPurchaseStatus(purchaseStatus+1);
        updateDmsPartsPurchaseOrder(dmsPartsPurchaseOrderNew);

        //如果是订单扣款需要去操作资金表
        if ((purchaseStatus+1) == 5 ){
            //1.获取经销商id(广州/深圳经销商），进行扣款
            Long dealerId = dmsPartsPurchaseOrder.getDealerId(); //经销商id
            Double purchasePrice = dmsPartsPurchaseOrder.getPurchasePrice(); //采购总价
            //查询经销商的资金并判断是否够钱，够才更新数据
            DmsFund dmsFund = new DmsFund();
            dmsFund.setFundOwnerId(dealerId);
            List<DmsFund> dmsFundList = iDmsFundService.selectDmsFundList(dmsFund);
            if (CollUtil.isEmpty(dmsFundList)){
                throw new ServiceException("查询不到账户："+dealerId);
            }
            dmsFund = dmsFundList.get(0);
            Double fund = dmsFund.getFund();//账户资金
            Double fundResult = fund-purchasePrice;//扣款后的金额
            //① 不够钱
            if (fundResult < 0.00){
                throw new ServiceException("账户："+dealerId+" 金额不足，无法扣款");
            }
            //② 够钱
            dmsFund.setFund(fundResult);
            iDmsFundService.updateDmsFund(dmsFund);

            //2.把扣款记录写入，资金记录表
            DmsFundRecord dmsFundRecord = new DmsFundRecord();
            dmsFundRecord.setFundOwnerId(dealerId);
            //填入资金方所属方名称、和类型
            if(dealerId==201){
                dmsFundRecord.setFundOwnerType(0);
                dmsFundRecord.setFundOwnerName(0);
            }
            else if (dealerId==101){
                dmsFundRecord.setFundOwnerType(1);
                dmsFundRecord.setFundOwnerName(1);
            }
            else if (dealerId==102){
                dmsFundRecord.setFundOwnerType(1);
                dmsFundRecord.setFundOwnerName(2);
            }
            dmsFundRecord.setConsumerFund(purchasePrice);
            dmsFundRecord.setConsumerId(SecurityUtils.getLoginUser().getUser().getUserId());
            dmsFundRecord.setConsumerName(SecurityUtils.getLoginUser().getUser().getUserName());
            dmsFundRecord.setConsumerTime(new Date());
            iDmsFundRecordService.updateDmsFundRecord(dmsFundRecord);
        }
        return true;
    }
}
